package com.sgidi.einvoice.service;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 专用于处理电子发票识别的类
 */

public class PdfAmountExtractor {

    static private String getPdfFirstPageText(PDDocument doc) throws IOException {
        PDFTextStripper textStripper = new PDFTextStripper();
        textStripper.setStartPage(1);
        textStripper.setEndPage(1);
        textStripper.setSortByPosition(true);
        String fullText = textStripper.getText(doc);
        return replace(fullText).replaceAll("（", "(").replaceAll("）", ")").replaceAll("￥", "¥");
    }

    public static double extract(PDDocument doc) throws IOException {
        String allText = getPdfFirstPageText(doc);
        {
            String reg = "小写\\D*(?<amount>\\d*\\.\\d\\d)";
            Pattern pattern = Pattern.compile(reg);
            Matcher matcher = pattern.matcher(allText);
            if (matcher.find()) {
                try {
                    return new Double(matcher.group("amount"));
                } catch (Exception e) {
                    return 0;
                }
            }
        }
        return 0;
    }

    private static String replace(String str) {
        return str.replaceAll(" ", "").replaceAll("　", "").replaceAll("：", ":").replaceAll(" ", "");
    }
}